<?php
/**
 * 订单服务层
 * @author maniac
 */

namespace app\common\service;

use app\common\model\Freight;
use app\common\model\OrderBank;
use app\common\model\OrderBank as OrderBankModel;
use app\common\model\OrdersRefund;
use app\common\model\OrdersRefund as OrdersRefundModel;
use app\common\model\WechatUsers AS WechatUsersModel;
use app\common\model\MemberAddresses AS MemberAddressesModel;
use app\common\model\Orders AS OrdersModel;
use app\common\model\MemberYongjin as MemberYongjinModel;
use app\common\model\Goods AS GoodsModel;
use app\common\model\GoodSku AS GoodSkuModel;
use app\common\model\OrderGoods AS OrderGoodsModel;
use app\common\model\OrderRefundGoods AS OrderRefundGoodsModel;
use app\common\model\Members AS MembersModel;
use app\common\model\MemberPoints AS MemberPointsModel;
use app\common\model\MemberVouchers AS MemberVouchersModel;
use app\common\model\MemberBalance AS MemberBalanceModel;
use app\common\model\Buycar AS BuycarModel;
use app\facade\Buycar AS BuycarFacade;
use app\facade\Wechat AS WechatFacade;
use app\facade\Options AS OptionsFacade;
use app\facade\Site AS SiteFacade;
use app\facade\Members AS MembersFacade;
use app\facade\CouponMe as CouponMeFacade;
use app\facade\Distribution;
use app\common\model\ActivityGoods as ActivityGoodsModel;
use app\common\model\Stores;
class Orders extends Base
{
    /*
     * 生成订单号
     *
     *$prefix   string  前缀
     *$uid      int     用户ID
     *
     * */
    public function order_no($prefix = 'BUY',$uid){
        $order_no = $prefix.date("YmdHis").intval($uid).mt_rand(1000,9999);
        return $order_no;
    }


    /**
     * 确认订单
     * @param $data
     */
    public function confirmOrder($data)
    {
        if (!is_array($data['goods'])) {
            $data['goods'] = json_decode($data['goods'], true);
        }
        $goods_ids = array_column($data['goods'],"goods_id");
        $where = [
            ['id', 'in', $goods_ids],
        ];
        $goods_mod = new  GoodsModel();
        $goods = $goods_mod->getList($where,'id,goods_name,goods_thumb_id,sale_price','',['image_uri']);
        if (empty($goods) || count($goods) == 0) {
            exception('商品不存在');
        }
        $orderAmount = array_sum(array_column($goods,"sale_price"));
        $orderInfo["goods"] = $goods;
        $orderInfo["orderAmount"] = $orderAmount;
        return $orderInfo;
    }

	/**
	 * 邮费
	 * @param $data
	 */
	public function confirmPostage($data)
	{
		if (!is_array($data['goods'])) {
			$data['goods'] = json_decode($data['goods'], true);
		}
		$goods_mod = new  GoodsModel();
		$postage_amount = [];
		$stores = explode(',',$data['store_id']);
		foreach ($stores as $sk=>$sv){
			$postage_amount[$sk]['amount'] = 0;
			foreach ($data['goods'] as $k => $v){
				$goods = $goods = $goods_mod->get_info(['id'=>$v['goods_id']],'id,sale_price,postage_id,goods_weight',['postage']);

				if(!$goods){

					exception('商品不存在');
				}

				if($v['goods_sku_id']){
					$where = [
						['id', 'eq', $v['goods_sku_id']],
						['goods_id', 'eq', $v['goods_id']],
					];

					$sku = GoodSkuModel::field('id,goods_id,sale_price')->where($where)->find();

					if(!$sku){
						exception('商品不存在');
					}
					$goods['sale_price'] = $sku['sale_price'];
				}
				$amount = 0;
				if($goods['postage_id']>0){//不包邮
					if($goods['postage_id'] == 1){//统一收费
						$amount = $goods['postage']['postage_amount'];
					}elseif($goods['postage_id'] ==2){//计重
						$weight = $goods['goods_weight']*$v['goods_nums'];
						if($weight > $goods['postage']['weight']){
							$c_weight = ceil($weight - $goods['postage']['weight']);
							$amount = $goods['postage']['potage_amount'] + $c_weight*$goods['postage']['weight_amount'];
						}
					}elseif($goods['postage_id'] ==3){//计件
						$amount = $goods['postage']['potage_amount'] * $v['goods_nums'];
					}else{//特殊
						if($data['address']){
							$address = MemberAddressesModel::where('id',$data['address'])->value('province');
							if(in_array($address,$goods['postage']['area'])){
								$amount = $goods['postage']['postage_amount'];
							}
						}
					}

				}
				$postage_amount[$sk]['id'] = $sv;
				if($postage_amount[$sk]['amount'] < $amount){
					$postage_amount[$sk]['amount'] = $amount;
				}
			}
		}
		return $postage_amount;
	}




    /**
     * 添加订单
     * @param array $data 请求的信
     */
    public function add($data)
    {
//        $data['userid'] = 2;
        //库存验证
        $is_goods_stock = false;
        if (!is_array($data['goods'])) {
            $data['goods'] = json_decode($data['goods'], true);
        }
        // 会员信息
        $user = MembersModel::field('id,role_id,points,username,nickname,wechat_id')->where('id', $data['userid'])->find();
        // 收货地址信息
        $address = MemberAddressesModel::field('name,mobile,province,city,district,address')
            ->append(['province_txt', 'city_txt', 'district_txt'])
            ->where('id', $data['user_address_id'])->find();
        $nickname = $user['nickname'] ? $user['nickname'] : $user['username'] ;
        $temp = [];      // 商品信息临时数组
        $goods_ids = array_column($data['goods'], 'goods_id'); //获取所有商品id
        $goods_mod = new  GoodsModel();
        $g_where[] = ['id','in',implode(',',$goods_ids)];//添加条件
        //获取所有商品
        $goods_list = $goods_mod->getList($g_where,'id,supplier_id,goods_name,cost_price,actual_sale_nums,goods_thumb_id,sale_price,give_points,goods_stock,goods_type,0 activity_id');

        $orderAmount = 0;

        //循环商品
        foreach ($data['goods'] as $v) {
            //循环获取商品列表
            foreach ($goods_list as $gk => $gv) {
                //判断商品id 等于 商品列表id
                if ($v['goods_id'] == $gv['id']) {
                        $v['goods_type'] = $gv['goods_type'];
                        $v['goods_name'] = $gv['goods_name'];
                        $v['image_uri'] = attach_uri($gv['goods_thumb_id']);
                        $v['sale_price'] = $gv['sale_price'];
                        $v['goods_sku_name'] = '';
                        $orderAmount += $gv['sale_price'] * $v['goods_nums'];
                        //更新商品兑换量
                        GoodsModel::where("id",$gv['id'])->update([
                            'actual_sale_nums' => $gv['actual_sale_nums'] + $v['goods_nums']
                        ]);
                }
            }
            $temp[] = $v;
        }
        if ($orderAmount > $user['points']){
            exception("积分不足");
        }
        $coupon_amount = 0;

        $data['points']   = 0;
        $data['vouchers'] = 0;
        $data['balance']  = 0;
        $data['order_no']           = $this->order_no('BUY',$data['userid']);
        $data['out_trade_no']       = unid();
        $data['username']           = $nickname;
        $data['receiver_name']      = $address['name'];
        $data['receiver_mobile']    = $address['mobile'];
        $data['receiver_province']  = $address['province_txt'];
        $data['receiver_city']      = $address['city_txt'];
        $data['receiver_district']  = $address['district_txt'];
        $data['receiver_address']   = $address['address'];
        $data['order_amount']       = $orderAmount;
		$data['postage_amount'] = 0;//邮费
		$data['pay_amount']         = $orderAmount;
        $data['pay_type']           = 1;
        $data['pay_status']         = 1;
        $data['pay_time']           = time();
        $data['coupon_amount']      = $coupon_amount;
        $order                      = OrdersModel::create($data);
        //值为真 为票务系统 验证身份证通过 添加信息
        if ($order->id) {
            $orderGoods = [];
                foreach ($temp as $k => $v) {
                    $orderGoods[] = [
                        'order_id'    => $order->id,
                        'goods_id'    => $v['goods_id'],
                        'goods_name'  => $v['goods_name'],
                        'sku_id'      => 0,
                        'sku_name'    => "",
                        'cost_price'  => 0,
                        'sale_price'  => $v['sale_price'],
                        'goods_nums'  => $v['goods_nums'],
                        'give_points' => 0,
                        'image_uri'   => $v['image_uri'],
                        'goods_type'  => 1,
                    ];
                }
            (new OrderGoodsModel)->saveAll($orderGoods);
            //添加积分记录
            (new PointsService())->SaveMemberPoints($user['id'],"-".$orderAmount,1,0,1,"兑换商品扣除积分");
            //重算用户积分
            (new PointsService())->RecalculationMemberPoints($user['id']);
            return true;
        }
        exception('添加订单失败');
    }

    /*
     * 退款
     * @param int    $userId   用户 id
     * @param int    $order_ids 订单ID
     * @param string    $order_ids 订单商品ID 字符串
     * */
    public function refund($userId,$order_id,$order_ids,$arr){
        if (!$userId) {
            exception('请先登录');
        }
        $order_mod = new  OrdersModel();
        $o_where[] = ['id','eq',$order_id];
        $orderinfo = $order_mod->get_info($o_where);
        if(!$orderinfo){
            exception('订单不存在');
        }
        if($orderinfo['pay_status'] == 2){
			exception('订单已申请过退款');
		}

        if($arr['r_type']==2){//申请退款/退货
            $data['order_status'] = 4;
        }else{//申请退款
            $data['order_status'] = 6;
        }

        $data['order_id'] = $order_id;
        $data['order_no'] = $orderinfo['order_no'];
        $data['parent_order'] = $orderinfo['parent_order'];
        $data['store_id'] = $orderinfo['store_id'];
        $data['store_name'] = $orderinfo['store_name'];
        $data['userid'] = $orderinfo['userid'];
        $data['username'] = $orderinfo['username'];
        $data['order_amount'] = $orderinfo['order_amount'];
        $data['pay_amount'] = $orderinfo['pay_amount'];
        $data['balance'] = $orderinfo['balance'];
        $data['create_time'] = time();
        $data['pay_status'] = 2;
        $data['user_message'] =$arr['user_message'];

        $order = OrdersRefundModel::create($data);
//        $datas = OrderGoodsModel::field(true)->where('id','in',$order_ids)->select()->toArray();

        $datas = OrderGoodsModel::field(true)->where('order_id','eq',$order_id)->select()->toArray();
        if(!$datas){
            exception('订单商品不存在');
        }
        $money = 0;
        foreach ($datas as $key =>$val){
            unset($val['id']);
            $val['order_id'] = $order->id;
            $orders = OrderRefundGoodsModel::create($val);
            $money += $val['sale_price'] * $val['goods_nums'];
        }

        //更新订单状态
        $up_arr=[
            'order_status'=>$data['order_status'],
            'pay_status'=>2,
            'shipping_status'=>3,
            'apply_txt'=>$arr['user_message'],
        ];
        (new OrdersModel())->where('id',$order_id)->update($up_arr);

        $o = new OrdersRefundModel;
        $o->save(['order_amount'=>$money],['id'=>$order->id]);
        return 1;

    }

    /**
     * 填写物流单号
     */
    public function setWNumbers($arr){
        if (!$arr['userid']) {
            exception('请先登录');
        }
        $order_mod = new  OrdersModel();
        $o_where = ['id','eq',$arr['order_id']];
        $orderinfo = $order_mod->get_info($o_where);
        if(!$orderinfo){
            exception('订单不存在');
        }

        if($orderinfo['pay_status'] !=3){
            exception('请先申请退款哟');
        }

        if($orderinfo['back_wl_title'] &&  $orderinfo['back_wl_number']){
            exception('请勿重复添加物流单号哟！');
        }

        $save_arr=[
            'back_wl_title'=>$arr['back_company'],
            'back_wl_number'=>$arr['back_num'],
        ];

        $where=[
            ['id','eq',$arr['order_id']]
        ];
        $res= (new OrdersModel())->where($where)->save($save_arr);

        return $res;
    }


    /**
     * 获取订单详情
     * @param int $userId 用户 id
     * @param int $id     订单 id
     */
    public function orderInfo($id, $userId = 0)
    {
        if (!$userId) {
            exception('请先登录');
        }
        if (!$id) {
            exception('订单不存在');
        }
        $where[] = [
            ['id', 'eq', $id],
        ];
        if ($userId) {
            $where[] = [
                ['userid', 'eq', $userId],
            ];
        }
        $order_mod = new  OrdersModel();
        $orderinfo = $order_mod->get_info($where,'',['goods_list','order_status_txt']);

        return $orderinfo;
    }





    /**
     * 获取订单列表
     * @param int    $userId   用户 id
     * @param string $limit    分页条件
     * @param int    $tabIndex 索引
     */
    public function orderList($userId, $limit, $tabIndex, $isShipping = 0,$order_type)
    {

        if (!$userId) {
            exception('请先登录');
        }
        $where[] = [
            ['is_user_delete', 'eq', 0],
        ];


            $where[] = [
                ['userid', 'eq', $userId],
            ];


        switch ($tabIndex) {
            case 0:
                // 全部
                $where[] = [
                    ['order_status', 'neq', 2],
                ];
                break;
            case 1:
                // 待付款
                $where[] = [
                    ['order_status', 'eq', 1],
                    ['pay_status', 'eq', 0],
                ];
                break;
            case 2:
                // 待发货
                $where[] = [
                    ['order_status', 'eq', 1],
                    ['pay_status', 'eq', 1],
                    ['shipping_status', 'eq', 0],
                ];
                break;
            case 3:
                // 待收货
                $where[] = [
                    ['order_status', 'eq', 1],
                    ['pay_status', 'eq', 1],
                    ['shipping_status', 'eq', 1],
                ];
                break;
            case 4:
                // 已完成
                $where[] = [
                    ['order_status', 'eq', 255],
//                    ['is_evaluates','eq',1]
                ];
                break;
            case 5:
                // 未完成配送单
                $where[] = [
                    ['order_status', 'neq', 255],
                ];
                break;
            case 6:
                // 已完成配送单
                $where[] = [
                    ['order_status', 'eq', 255],
                ];
                break;
            case 7:
                // 未评论
                $where[] = [
                    ['order_status', 'eq', 255],
                    ['pay_status', 'eq', 1],
                    ['shipping_status','eq',2],
                    ['is_evaluates','eq',0]
                ];
                break;
            case 8:
                // 退款退货
                $where[] = [
                    ['order_status', 'in', [2,4,5,6,7]],
                    ['pay_status', 'in', [2,3,5]],
                    ['shipping_status','in',[3,4,5]]
                ];
                break;

        }


        $filed="id,order_no,pay_type,order_amount,pay_amount,order_status,pay_status,shipping_status,pay_time,send_time,sign_time,create_time,finish_time,0 o_status";
        $data = OrdersModel::field($filed)->append(['order_status_id', 'order_status_txt', 'goods_list','order_goods_count'])->where($where)->order('id DESC')->limit($limit)->select()->toArray();

        return $data;
    }

    /*商户的订单*/
    public function shop_orderList($userId, $limit, $tabIndex, $isShipping = 0)
    {
        if (!$userId) {
            exception('请先登录');
        }
        $where[] = [
            ['is_user_delete', 'eq', 0],
        ];
        if ($isShipping) {
            $where[] = [
                ['shipping_userid', 'eq', $userId],
            ];
        } else {
            $where[] = [
                ['store_id', 'eq', $userId],
            ];
        }
        switch ($tabIndex) {
            case 0:
                // 全部
                $where[] = [
                    ['order_status', 'neq', 2],
                ];
                break;
            case 1:
                // 待付款
                $where[] = [
                    ['order_status', 'eq', 1],
                    ['pay_status', 'eq', 0],
                ];
                break;
            case 2:
                // 待发货
                $where[] = [
                    ['order_status', 'eq', 1],
                    ['pay_status', 'eq', 1],
                    ['shipping_status', 'eq', 0],
                ];
                break;
            case 3:
                // 待收货
                $where[] = [
                    ['order_status', 'eq', 1],
                    ['pay_status', 'eq', 1],
                    ['shipping_status', 'eq', 1],
                ];
                break;
            case 4:
                // 已完成
                $where[] = [
                    ['order_status', 'eq', 255],
                    ['is_evaluates','eq',1]
                ];
                break;
            case 5:
                // 未完成配送单
                $where[] = [
                    ['order_status', 'neq', 255],
                ];
                break;
            case 6:
                // 已完成配送单
                $where[] = [
                    ['order_status', 'eq', 255],
                ];
                break;
            case 7:
                // 未评论
                $where[] = [
                    ['order_status', 'eq', 255],
                    ['pay_status', 'eq', 1],
                    ['shipping_status','eq',2],
                    ['is_evaluates','eq',0]
                ];
                break;
            case 8:
                // 退款退货
                $where[] = [
                    ['order_status', 'in', [2,4,5,6,7]],
                    ['pay_status', 'in', [2,3,5]],
                    ['shipping_status','in',[3,4,5]]
                ];
                break;

        }

        $filed="id,order_no,pay_type,order_amount,pay_amount,balance,points,vouchers,order_status,pay_status,shipping_status,pay_time,send_time,sign_time,create_time,finish_time,is_evaluates,0 o_status";
        $data = OrdersModel::field($filed)->append(['order_status_id', 'order_status_txt', 'goods_list'])->where($where)->order('id DESC')->limit($limit)->select()->toArray();
        return $data;
    }

    /**
     * 获取订单数量
     * @param string $id 标识
     */
    public function orderNums($id)
    {
        $where   = [];
        $whereOr = [];
        switch ($id) {
            case 'pay_status_0':
                $where = [
                    ['pay_status', 'eq', 0],
                ];
                break;
            case 'shipping_status_0':
                $whereOr = [
                    [
                        ['pay_type', 'neq', 2],
                        ['pay_status', 'eq', 1],
                        ['shipping_status', 'eq', 0],
                    ],
                    [
                        ['pay_type', 'eq', 2],
                        ['shipping_status', 'eq', 0],
                    ]
                ];
                break;
            case 'shipping_status_1':
                $where = [
                    ['shipping_status', 'eq', 1],
                ];
                break;
        }
        return OrdersModel::field('id')->where($where)->whereOr($whereOr)->count();
    }
    
    /**
     * 支付订单
     * @param int $userId 用户 id
     * @param int $id     订单 id
     */
    public function payOrder($userId, $id)
    {
        if (!$userId) {
            exception('请先登录');
        }
        if (!$id) {
            exception('订单不存在');
        }
        $order = $this->orderInfo($id, $userId);
        
        if (!$order) {
            exception('订单不存在');
        }
        
        if ($order['pay_status']) {
            exception('该订单已支付');
        }
        $member          = MembersModel::field('id,role_id,points,balance')->where('wechat_id', $order['userid'])->find();
        $user            = WechatUsersModel::field('openid')->where('id', $order['userid'])->find();
        $order['openid'] = $user['openid'];
        $order['platform'] = 'JSAPI';

        $wechat          = WechatFacade::unifiedorder($order);
        $result['wxpay'] = [
            'timeStamp' => $wechat['timeStamp'],
            'nonceStr'  => $wechat['nonceStr'],
            'package'   => $wechat['package'],
            'paySign'   => $wechat['paySign'],
        ];
        return $result;
    }
    
    /**
     * 确认收货
     * @param int $userId 用户 id
     * @param int $id     订单 id
     */
    public function confirmGoods($userId, $id)
    {
        if (!$userId) {
            exception('请先登录');
        }
        if (!$id) {
            exception('订单不存在');
        }
        $order = $this->orderInfo($id, $userId);
        
        if (!$order) {
            exception('订单不存在');
        }
        
        if ($order['order_status'] == 255) {
            exception('该订单已完成');
        }
        
        $order->shipping_status = 2;
        $order->order_status    = 255;
        $order->sign_time       = time();
        $order->finish_time     = time();
        if ($order->save()) {
//            $data = [
//
//                'id'=>$userId,
//
//                'key'=>'points',
//
//                'value'=>intval($order['pay_amount']),
//
//                'remark'=>'购物赠送积分',
//
//                'surplus' => intval($order['pay_amount']),
//
//                'sort' => 1,
//
//            ];
//            \app\facade\Members::balanceChange($data);
//
//            Distribution::distribution_commission($userId,$id);//返佣

            return true;
        }
        return false;
    }
    
    /**
     * 指派配送员
     * @param int $id     订单 id
     * @param int $userid 配送员用户 id
     */
    public function allot($id, $userid)
    {
        $order = OrdersModel::field('id,shipping_userid')->where('id', $id)->find();
        if (!$order) {
            exception('订单不存在');
        }
        $order->shipping_userid = $userid;
        if ($order->save()) {
            // TODO: 发送模板消息
            return true;
        }
        return false;
    }
    
    /**
     * 导出订单信息
     * @param array $where 查询条件
     */
    public function export($where)
    {
        $orders = OrdersModel::field(true)->where($where)->select();
        $result = [];
        foreach ($orders as $k => $v) {
            $result[$k]['header'] = '订单编号：'.$v['order_no'];
            $result[$k]['value']  = [
                'A' => $v['out_trade_no'],
                'B' => $v['transaction_id'],
                'C' => $v['pay_type_name'],
                'D' => $v['username'],
                'E' => $v['user_message'],
                'F' => $v['receiver_name'],
                'G' => $v['receiver_mobile'],
                'H' => $v['receiver_province'].$v['receiver_city'].$v['receiver_district'].$v['receiver_address'],
                'I' => $v['order_amount'],
                'J' => $v['pay_amount'],
//                'I' => $v['shipping_time'],
//                'J' => $v['shipping_user'],
//                'K' => $v['order_amount'],
//                'L' => $v['pay_amount'],
//                'M' => $v['points'],
//                'N' => $v['vouchers'],
//                'O' => $v['order_status_txt'],
//                'P' => $v['pay_time_date'],
//                'Q' => $v['send_time_date'],
//                'R' => $v['sign_time_date'],
//                'S' => $v['finish_time_date'],
            ];
            $result[$k]['goods_list'] = $v['goods_list'];
        }

        $title = [
            'A' => '第三方单号',
            'B' => '第三方支付单号',
            'C' => '支付方式',
            'D' => '下单会员',
            'E' => '会员留言',
            'F' => '收货人姓名',
            'G' => '收货人电话',
            'H' => '收货人地址',
            'I' => '订单金额',
            'J' => '实付金额',
//            'I' => '配送时间',
//            'J' => '配送会员',
//            'K' => '订单金额',
//            'L' => '实付金额',
//            'M' => '积分支付',
//            'N' => '抵用券支付',
//            'O' => '订单状态',
//            'P' => '支付时间',
//            'Q' => '发货时间',
//            'R' => '签收时间',
//            'S' => '完成时间',
        ];
        $title1 = [
            'A' => '商品名称',
            'B' => '商品 sku',
            'C' => '成本价',
            'D' => '销售价',
            'E' => '数量',
        ];
        $objPHPExcel = new \PHPExcel();
        $flag        = true;
        $i           = 1;
        while ($flag) {
            foreach ($result as $key => $val) {
                // 表头，合并单元格
                $objPHPExcel->getActiveSheet()->mergeCells('A'.$i.':S'.$i);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$i, $val['header']);
                $objPHPExcel->getActiveSheet()->getStyle('A'.$i)->getFont()->getColor()->setRGB('0070C0');
                $objPHPExcel->getActiveSheet()->getStyle('A'.$i)->getFont()->setName('Microsoft YaHei');
                $i++;
                
                // 表格标题
                foreach ($title as $k => $v) {
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($k.$i, $v);
                    $objPHPExcel->getActiveSheet()->getColumnDimension($k)->setWidth(30);
                    $objPHPExcel->getActiveSheet()->getStyle($k.$i)->getFont()->getColor()->setRGB('0070C0');
                    $objPHPExcel->getActiveSheet()->getStyle($k.$i)->getFont()->setName('Microsoft YaHei');
                }
                $i++;
                
                foreach ($val['value'] as $k => $v) {
                    $objPHPExcel->getActiveSheet()->getStyle($k.$i)->getFont()->setName('Microsoft YaHei');
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValueExplicit($k.$i, $v, \PHPExcel_Cell_DataType::TYPE_STRING);
                }
                $i++;
                // 表格标题
                foreach ($title1 as $k1 => $v1) {
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($k1.$i, $v1);
                    $objPHPExcel->getActiveSheet()->getColumnDimension($k1)->setWidth(30);
                    $objPHPExcel->getActiveSheet()->getStyle($k1.$i)->getFont()->getColor()->setRGB('7000C0');
                    $objPHPExcel->getActiveSheet()->getStyle($k1.$i)->getFont()->setName('Microsoft YaHei');
                }
                $i++;
                if ($val['goods_list']) {
                    foreach ($val['goods_list'] as $k1 => $v1) {
                        $objPHPExcel->getActiveSheet()->getStyle('A'.$i)->getFont()->setName('Microsoft YaHei');
                        $objPHPExcel->getActiveSheet()->getStyle('B'.$i)->getFont()->setName('Microsoft YaHei');
                        $objPHPExcel->getActiveSheet()->getStyle('C'.$i)->getFont()->setName('Microsoft YaHei');
                        $objPHPExcel->getActiveSheet()->getStyle('D'.$i)->getFont()->setName('Microsoft YaHei');
                        $objPHPExcel->getActiveSheet()->getStyle('E'.$i)->getFont()->setName('Microsoft YaHei');
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValueExplicit('A'.$i, $v1['goods_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValueExplicit('B'.$i, $v1['sku_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValueExplicit('C'.$i, 0 , \PHPExcel_Cell_DataType::TYPE_STRING);
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValueExplicit('D'.$i, $v1['sale_price'], \PHPExcel_Cell_DataType::TYPE_STRING);
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValueExplicit('E'.$i, $v1['goods_nums'], \PHPExcel_Cell_DataType::TYPE_STRING);
                        $i++;
                    }
                } else {
                    $i++;
                }
                $i++;
            }
            $flag = false;
        }
        
        $objPHPExcel->getActiveSheet()->setTitle('Simple');
        $objPHPExcel->setActiveSheetIndex(0);
        
        // Redirect output to a client’s web browser (Excel5)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="订单.xls"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }


    /**
     * 取消订单
     * @param string $userId 用户id
     * @param string $orderid 订单id
     */
    public function cancelOrder($userId,$orderid)
    {
        $where    = [
            ['id', 'eq', $orderid],
            ['userid', 'eq', $userId],
        ];
        $orders = OrdersModel::field('id,order_status')->where($where)->select();
        if (count($orders)) {
            $update   = [];
            $orderIds = [];
            foreach ($orders as $v) {
                $orderIds[] = $v['id'];
                $update[]   = [
                    'id'           => $v['id'],
                    'order_status' => 2
                ];
            }
            (new OrdersModel)->saveAll($update);

            $where      = [
                ['order_id', 'in', $orderIds],
            ];
            $orderGoods = OrderGoodsModel::field('goods_id,sku_id,goods_nums')->where($where)->select();
            $orderGoods = count($orderGoods) ? $orderGoods->toArray() : [];
            if (!empty($orderGoods)) {
                $tempGoods = [];
                $tempSku   = [];
                foreach ($orderGoods as $v) {
                    if (isset($tempGoods[$v['goods_id']])) {
                        $tempGoods[$v['goods_id']]['goods_nums'] += $v['goods_nums'];
                    } else {
                        $tempGoods[$v['goods_id']] = $v;
                    }
                    if ($v['sku_id']) {
                        if (isset($tempSku[$v['sku_id']])) {
                            $tempSku[$v['sku_id']]['goods_nums'] += $v['goods_nums'];
                        } else {
                            $tempSku[$v['sku_id']] = $v;
                        }
                    }
                }

                $where       = [
                    ['id', 'in', array_keys($tempGoods)],
                ];
                $goodsUpdate = [];
                $goods       = GoodsModel::field('id,goods_stock')->where($where)->select();
                foreach ($goods as $v) {
                    $goodsUpdate[] = [
                        'id'          => $v['id'],
                        'goods_stock' => $v['goods_stock'] + $tempGoods[$v['id']]['goods_nums'],
                    ];
                }
                (new GoodsModel)->saveAll($goodsUpdate);

                $where     = [
                    ['id', 'in', array_keys($tempSku)],
                ];
                $skuUpdate = [];
                $sku       = GoodSkuModel::field('id,goods_id,stock')->where($where)->select();
                foreach ($sku as $v) {
                    $skuUpdate[] = [
                        'id'    => $v['id'],
                        'stock' => $v['stock'] + $tempSku[$v['id']]['goods_nums'],
                    ];
                }
                (new GoodSkuModel)->saveAll($skuUpdate);
            }
            return true;
        }
        return false;
    }


    
    /**
     * 取消订单
     */
    public function cancelOrders()
    {
        $where    = [
            ['pay_type', 'neq', 2],
            // ['order_status', 'neq', 2],
            ['pay_status', 'eq', 0],
            ['create_time', 'elt', time() - 30*60],
        ];
        $orders = OrdersModel::field('id,order_status')->where($where)->select();
        if (count($orders)) {
            $update   = [];
            $orderIds = [];
            foreach ($orders as $v) {
                $orderIds[] = $v['id'];
                $update[]   = [
                    'id'           => $v['id'],
                    'order_status' => 2
                ];
            }
            (new OrdersModel)->saveAll($update);
            
            $where      = [
                ['order_id', 'in', $orderIds],
            ];
            $orderGoods = OrderGoodsModel::field('goods_id,sku_id,goods_nums')->where($where)->select();
            $orderGoods = count($orderGoods) ? $orderGoods->toArray() : [];
            if (!empty($orderGoods)) {
                $tempGoods = [];
                $tempSku   = [];
                foreach ($orderGoods as $v) {
                    if (isset($tempGoods[$v['goods_id']])) {
                        $tempGoods[$v['goods_id']]['goods_nums'] += $v['goods_nums'];
                    } else {
                        $tempGoods[$v['goods_id']] = $v;
                    }
                    if ($v['sku_id']) {
                        if (isset($tempSku[$v['sku_id']])) {
                            $tempSku[$v['sku_id']]['goods_nums'] += $v['goods_nums'];
                        } else {
                            $tempSku[$v['sku_id']] = $v;
                        }
                    }
                }
                
                $where       = [
                    ['id', 'in', array_keys($tempGoods)],
                ];
                $goodsUpdate = [];
                $goods       = GoodsModel::field('id,goods_stock')->where($where)->select();
                foreach ($goods as $v) {
                    $goodsUpdate[] = [
                        'id'          => $v['id'],
                        'goods_stock' => $v['goods_stock'] + $tempGoods[$v['id']]['goods_nums'],
                    ];
                }
                (new GoodsModel)->saveAll($goodsUpdate);
                
                $where     = [
                    ['id', 'in', array_keys($tempSku)],
                ];
                $skuUpdate = [];        
                $sku       = GoodSkuModel::field('id,goods_id,stock')->where($where)->select();
                foreach ($sku as $v) {
                    $skuUpdate[] = [
                        'id'    => $v['id'],
                        'stock' => $v['stock'] + $tempSku[$v['id']]['goods_nums'],
                    ];
                }
                (new GoodSkuModel)->saveAll($skuUpdate);
            }
        }
    }

	/**
	 * 取消拼团订单
	 */
	public function cancelActivityOrders()
	{
		$where    = [
			['pay_status', 'eq', 1],
			['activity_enddt', 'elt', time()],
			['activity_status', 'eq', 0],
		];
		$orders = OrdersModel::field('id,userid,pay_amount,order_status,activity_status')->where($where)->select();
		if (count($orders)) {
			$update   = [];
			$orderIds = [];
			foreach ($orders as $v) {
				$orderIds[] = $v['id'];
				$update[]   = [
					'id'           => $v['id'],
					'order_status' => 2,
					'activity_status' => 2,
				];
				$data = [

					'id'=>$v['userid'],

					'key'=>'balance',

					'value'=>$v['pay_amount'],

					'remark'=>'拼图失败返回余额',

				];
				MembersFacade::balanceChange($data);
			}
			(new OrdersModel)->saveAll($update);

			$where      = [
				['order_id', 'in', $orderIds],
			];
			$orderGoods = OrderGoodsModel::field('goods_id,sku_id,goods_nums')->where($where)->select();
			$orderGoods = count($orderGoods) ? $orderGoods->toArray() : [];
			if (!empty($orderGoods)) {
				$tempGoods = [];
				$tempSku   = [];
				foreach ($orderGoods as $v) {
					if (isset($tempGoods[$v['goods_id']])) {
						$tempGoods[$v['goods_id']]['goods_nums'] += $v['goods_nums'];
					} else {
						$tempGoods[$v['goods_id']] = $v;
					}
					if ($v['sku_id']) {
						if (isset($tempSku[$v['sku_id']])) {
							$tempSku[$v['sku_id']]['goods_nums'] += $v['goods_nums'];
						} else {
							$tempSku[$v['sku_id']] = $v;
						}
					}
				}

				$where       = [
					['id', 'in', array_keys($tempGoods)],
				];
				$goodsUpdate = [];
				$goods       = GoodsModel::field('id,goods_stock')->where($where)->select();
				foreach ($goods as $v) {
					$goodsUpdate[] = [
						'id'          => $v['id'],
						'goods_stock' => $v['goods_stock'] + $tempGoods[$v['id']]['goods_nums'],
					];
				}
				(new GoodsModel)->saveAll($goodsUpdate);

				$where     = [
					['id', 'in', array_keys($tempSku)],
				];
				$skuUpdate = [];
				$sku       = GoodSkuModel::field('id,goods_id,stock')->where($where)->select();
				foreach ($sku as $v) {
					$skuUpdate[] = [
						'id'    => $v['id'],
						'stock' => $v['stock'] + $tempSku[$v['id']]['goods_nums'],
					];
				}
				(new GoodSkuModel)->saveAll($skuUpdate);
			}
		}

	}





    /*
     * 订单核销码
     *
     * $orderid  int  订单ID
     *
     * */
    public function order_code($orderid){


        $rootPath = str_replace('\\', '/', Env::get('root_path'));
        require $rootPath . 'extend/phpqrcode/phpqrcode.php';
        $file = './static/uploads/qrcode/order_' . $orderid . '.png';
        $value = config('system.attach_uri_prefix') . 'mob?id=' . $orderid;
        $errorCorrectionLevel = "L";
        $matrixPointSize = 10;
        \QRcode::png($value, $file, $errorCorrectionLevel, $matrixPointSize, 2);
        return config('system.attach_uri_prefix') . ltrim($file, './');

    }

    /*
     * 订单核销
     *
     * $userId  int  用户ID
     * $orderid  int  订单ID
     *
     * */
    public function is_verification($userId,$orderid){
        $info = MembersFacade::info($userId);
        if($info['is_verification'] == 0){
            exception('您不是核销员，暂不能操作');
        }
        $order = OrderVerification::field(true)->where('id',$orderid)->find();
        if(!$order){
            exception('订单不存在');
        }
        if($order['verification_status'] ==1 ){
            exception('订单已核销过，不能重复核销');
        }
        $create = array(
            'userid' =>$userId,
            'order_id' =>$order['order_id'],
            'verification_id' =>$orderid,
            'nickname' =>$info['nickname'],
            'mobile' =>$info['mobile'],
            'create_time' =>time(),
        );

    }

    /*
     *核销列表
     *
     * $userid  int  用户ID
     * $type  int  状态
     *
     *  */
    public function order_verification($userid,$type){
        $where = [
            ['userid','eq',$userid],
            ['verification_status','eq',$type]
        ];
        $list = OrderVerification::field(true)->where($where)->select();
        return $list;
    }


}
